package com.duan.goods.listener;

import com.alibaba.fastjson.JSONObject;
import com.duan.goods.config.RabbitMqConfig;
import com.duan.goods.service.ProductDetailsService;
import com.duan.order.pojo.Order;
import com.duan.order.pojo.Task;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class listener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductDetailsService productDetailsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RabbitListener(queues = RabbitMqConfig.ORDER_QUEUE)
    public void order(String message) {
        Task task = JSONObject.parseObject(message, Task.class);
        //判断redis中是否有此任务(根据taskId)
        Object o = redisTemplate.opsForValue().get(task.getId());
        if (o != null) {
            //有此消息直接返回，不做处理
            return;
        }
        //没有此消息，将此消息存入redis中
        redisTemplate.opsForValue().set(task.getId(), task.getId(), 5, TimeUnit.MINUTES);
        //处理业务(减库存)
        String requestBody = task.getRequestBody();
        Order order = JSONObject.parseObject(requestBody, Order.class);
        Integer i = productDetailsService.reducedInventory(order.getProductId(), order.getNum());
        if (i != 1) {
            //库存不足，回滚
            rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE, RabbitMqConfig.ERROR_QUEUE, order.getId());

        }
        //9、如果只有一个消费者，taskid存入到redis中时加上过期时间5分钟。如果多个消费者则不用
        //10、删除redis中的信息(单个消费者不用执行)
        //11、全部执行成功后给MQ发消息
        rabbitTemplate.convertAndSend(RabbitMqConfig.TASK_EXCHANGE, RabbitMqConfig.TASK_QUEUE, task.getId());
    }
}
